package com.eshore.norm.pattern.singleton.demo1;

/**
 * 单例模式-懒汉式
 *
 * @author: v-chenjl62
 * @date: 2024/1/30 15:47
 */
public class Singleton {

    //static保证 每个线程改动值可见，不会进来变回false初始值
    private static boolean flag = false;

    //1.私有构造方法
    private Singleton() {
        //反射破解单例模式需要添加的代码
        synchronized (Singleton.class) {
            if (flag) {
                throw new RuntimeException();
            }
            flag = true;
        }
    }

    //2.创建本类对象
    private static volatile Singleton singleton;

    //3.提供一个公共访问方法
    public static Singleton getInstance() {
        if (singleton == null) {
            synchronized (Singleton.class) {
                if (singleton == null) {
                    singleton = new Singleton();
                }
            }
        }
        return singleton;
    }


}
